package com.inspur.dgov.bsp.application.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inspur.dgov.bsp.application.entity.PubRole;
import com.inspur.dgov.bsp.application.entity.PubRoleResource;
import com.inspur.dgov.bsp.application.mapper.PubRoleMapper;
import com.inspur.dgov.bsp.application.service.PubRoleResourceService;
import com.inspur.dgov.bsp.application.service.PubRoleService;
import com.inspur.dgov.common.tool.utils.UniqueIdGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 角色信息 服务实现类
 *
 * @author chiyupei
 * @version 1.0
 * @since 1.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class PubRoleServiceImpl extends ServiceImpl<PubRoleMapper, PubRole> implements PubRoleService {

    private PubRoleResourceService pubRoleResourceService;

    /**
     * 角色分页数据
     * @param page
     * @param params
     * @return
     */
    @Override
    public IPage<PubRole> selectRolePage(Page page, Map<String, Object> params) {
        return baseMapper.selectRolePage(page, params);
    }

    /**
     * 权限配置
     *
     * @param roleId 角色id
     * @param menuIds 资源id集合
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean grant(String roleId, String menuIds) {
        // 删除角色配置的菜单集合
        this.pubRoleResourceService.remove(Wrappers.<PubRoleResource>update().lambda().eq(PubRoleResource::getRoleId, roleId));
        // 组装配置
        List<PubRoleResource> roleResources = new ArrayList<>();
        List<String> list = StrUtil.split(menuIds, ',');
        list.forEach(menuId -> {
            PubRoleResource roleResource = new PubRoleResource();
            roleResource.setId(UniqueIdGenerator.generateId());
            roleResource.setRoleId(Long.valueOf(roleId));
            roleResource.setResId(Long.valueOf(menuId));
            roleResources.add(roleResource);
        });
        // 新增配置
        return this.pubRoleResourceService.saveBatch(roleResources);
    }
}
